// UserProfileServlet.java
package com.onlineshop.controller;

import com.onlineshop.dao.UserDao;
import com.onlineshop.entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/profile")
public class UserProfileServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        request.getRequestDispatcher("/profile.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        String password = request.getParameter("password");
        String email = request.getParameter("email");

        // 更新用户信息
        currentUser.setPassword(password);
        currentUser.setEmail(email);

        boolean success = userDao.updateUser(currentUser);
        if (success) {
            session.setAttribute("user", currentUser);
            request.setAttribute("success", "个人信息更新成功");
        } else {
            request.setAttribute("error", "更新失败，请重试");
        }
        request.getRequestDispatcher("/profile.jsp").forward(request, response);
    }
}